<template>
  <div class="KnockOut">
    <!--背景-->
    <div class="bg"></div>
    <img style="width: 100%;" :src="bannerurl" v-if="bannerurl" />
    <!-- 页面主体信息区域 -->
    <div class="outermostMargin">
      <van-cell-group :border="false">
        <van-field
          required
          class="messageBox"
          v-model="fieldValues.adviseContent"
          rows="4"
          autosize
          type="textarea"
          maxlength="500"
          placeholder="请输入问题详情描述……(最少输入10个字符)"
          show-word-limit
          :error-message="formDebug && fieldValues.adviseContent.length < 10 ? '最少输入10个字符' : ''"
        />
      </van-cell-group>
      <div style="height: 10px;"></div>
      <van-cell-group :border="false">
        <van-uploader
          :max-count="9"
          v-if="fileList.length"
          class="uploader"
          v-model="fileList"
          multiple
        >
          <div></div>
        </van-uploader>
        <div class="etRowBox">
          <div class="etButton" @click="chooseImage(['album'])">
            <img slot="icon" src="@/assets/knockOut/knockOut(1).png" />
            <span class="ideText">照片</span>
          </div>
          <div class="etButton" @click="chooseImage(['camera'])">
            <img slot="icon" src="@/assets/knockOut/knockOut(2).png" />
            <span class="ideText">拍照</span>
          </div>
        </div>
      </van-cell-group>

      <van-cell-group :border="false">
        <van-field
          v-model="fieldValues.adress"
          clearable
          readonly
          clickable
          left-icon="location"
          right-icon="arrow"
          type="textarea"
          placeholder="请选地址"
          autosize
          rows="1"
          @click="$router.push('/TdMapSelectPoint')"
          @click-right-icon="$router.push('/TdMapSelectPoint')"
        />
      </van-cell-group>

      <van-cell-group style="margin-top: 12px;" :border="false">
        <van-field
          v-model="fieldValues.classification"
          required
          clearable
          readonly
          clickable
          right-icon="arrow"
          placeholder="请选择主题分类"
          @click="showPicker = true"
          @click-right-icon="showPicker = true"
        />
      </van-cell-group>

      <div class="buttons">
        <van-button type="default" class="butItem" @click="canselbut()">取消</van-button>
        <van-button type="info" class="butItem" @click="subbut()">提交</van-button>
      </div>
    </div>
    <!--弹出菜单-->
    <van-action-sheet
      @select="select"
      v-model="showPicker"
      :actions="actions"
      cancel-text="取消"
      @cancel="showPicker = false"
    />
  </div>
</template>
<script>
import bus from "../../plugins/eventBus.js";
var _self;
export default {
  name: "knockOut",
  data() {
    var location = {
      address: "东营市河口区黄河路",
      longitude: 31,
      latitude: 12
    };
    if (this.slow.location.latitude) {
      location = this.slow.location;
    }
    return {
      showPicker: false,
      actions: [],
      formDebug: false,
      bannerurl: "",
      fieldValues: {
        classification: "",
        adviseNameId: "",
        adviseContent: "",
        adviseName: "",
        attachments: "",
        dataAreaCode: "",
        adress: location.address,
        x: location.longitude,
        y: location.latitude,
        adviseType: ""
      },
      fileList: [],
      location: location
    };
  },
  mounted() {
    let that = this;
  },
  created() {
    _self = this;
    // alert("isAuth:" + sessionStorage.getItem("isAuth"));
    /**
     * 获取数据字典值
     */
    this.slow.getDictionaryValus("adviseType").then(ret => {
      ret.forEach(e => {
        e.name = e.text;
      });
      this.actions = ret;
    });

    this.slow.getBanner("我要报事", url => {
      this.bannerurl = url;
    });
  },
  activated() {
    if (window.sessionStorage.getItem("location")) {
      this.location = JSON.parse(window.sessionStorage.getItem("location"));
      this.fieldValues.adress = this.location.address;
      this.fieldValues.x = this.location.longitude;
      this.fieldValues.y = this.location.latitude;
    }
  },
  methods: {
    select(item, index) {
      this.fieldValues.classification = item.name;
      this.fieldValues.adviseType = item.value;
      this.showPicker = false;
      console.log("adviseType select", this.fieldValues.adviseType);
    },
    back() {
      this.$router.isBack = true; // 将返回状态置为触发态，以边路由监听触发返回动画
      this.$router.back();
    },
    chooseImage(sourceType = ["album", "camera"]) {
      wx.chooseImage({
        count: 1, // 默认9
        sizeType: ["original", "compressed"], // 可以指定是原图还是压缩图，默认二者都有
        sourceType: sourceType, // 可以指定来源是相册还是相机，默认二者都有
        success: function(res) {
          var localIds = res.localIds; // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
          wx.uploadImage({
            localId: localIds[0], // 需要上传的图片的本地ID，由chooseImage接口获得
            isShowProgressTips: 1, // 默认为1，显示进度提示
            success: function(resUpImg) {
              var serverId = resUpImg.serverId; // 返回图片的服务器端ID
              let webType = _self.slow.isWebview();
              if (webType === "wechat-android") {
                _self.fileList.push({
                  url: localIds[0],
                  serverId: serverId,
                  isImage: true
                });
              } else if (webType === "wechat-ios") {
                wx.getLocalImgData({
                  localId: localIds[0], // 图片的localID
                  success: function(resImgData) {
                    var localData = resImgData.localData; // localData是图片的base64数据，可以用img标签显示
                    _self.fileList.push({
                      url: localData,
                      serverId: serverId,
                      isImage: true
                    });
                  },
                  fail: function(err) {
                    alert(JSON.stringify(err));
                  }
                });
              }
            }
          });
        }
      });
    },
    entranceTo(w) {
      switch (w) {
        // case 0:
        //   this.$router.push("");
        //   break;
        case 1:
          this.$router.push("/classification");
          break;
        default:
          this.$router.push("/home");
          break;
      }
    },
    /**
     * 附件上传
     */
    upload() {
      // alert("slow.openId:"+ this.slow.userInfo.openId)
      // alert("session.openId:"+ JSON.stringify(sessionStorage.getItem("userInfo")).openId)
      let rb = new Promise((reslove, reject) => {
        console.log("fileList , " + JSON.stringify(this.fileList));
        if (this.fileList.length) {
          var media_id = "";
          this.fileList.forEach(e => {
            if (!media_id) {
              media_id = e.serverId;
            } else {
              media_id = media_id + "," + e.serverId;
            }
          });
          this.$toast.loading({
            message: "附件提交中...",
            forbidClick: true
          });
          this.post("/subsystem/attach/upload_wx", {
            media_id: media_id,
            publicUserId: this.slow.userInfo.openId
          }).then(r => {
            this.$toast.clear();
            reslove(r.object);
          });
        } else {
          reslove("");
        }
      });
      return rb;
    },
    canselbut() {
      this.back();
    },
    subbut() {
      if (!this.slow.isAuth) {
      // if (!this.slow.isAuth || this.slow.userInfo.subscribe == 0) {
        this.$dialog
          .confirm({
            title: "提示",
            message: "您还没有认证，是否前去认证？"
          })
          .then(() => {
            this.$router.push("/register");
          })
          .catch(() => {
            // on cancel
          });
      } else {
        this.formDebug = true;
        if (this.fieldValues.adviseContent.length < 10) {
          this.$toast("最少输入10个字符");
          return;
        } else if (!this.fieldValues.classification) {
          this.$toast("请选择主题分类");
          return;
        }
        this.upload().then(attachments => {
          this.fieldValues.attachments = attachments;
          let userInfo = JSON.parse(sessionStorage.getItem("userInfo"));
          this.fieldValues.adviseName = this.slow.authObject.userName;
          this.fieldValues.dataAreaCode = this.slow.authObject.dataAreaCode;
          this.fieldValues.adviseNameId = userInfo.openId;
          this.post("/public_opinion/save", this.fieldValues)
            .then(r => {
              if (r.flag === "true") {
                this.$toast.success(r.message || "提交成功");
                setTimeout(() => {
                  this.$toast.clear();
                  this.$router.back();
                }, 2000);
              } else {
                this.$toast.fail(r.message || "提交失败");
              }
            })
            .catch(err => {
              this.$toast.fail("服务器未反应，请稍后重试");
            });
        });
      }
    }
  }
};
</script>
<style lang="scss" scoped>
@import "~@/smobile.scss";
.KnockOut {
  .uploader {
    margin-left: 10px;
    margin-top: 10px;
    margin-right: 10px;
  }
  .header {
    padding: $sm-spaceing-block-sm 0 $sm-spaceing-block-sm 0;

    position: absolute;
    width: $sm-img-per-max;
    height: 21px;
    background: $sm-bg-color;
    z-index: 2;

    display: flex;
    flex-direction: row nowrap;
    justify-content: flex-start;
    .backIcon {
      position: absolute;
      white-space: nowrap;
      height: $sm-icon-px-md;
      z-index: 4;

      .iconImage {
        height: $sm-icon-px-md;
        width: $sm-icon-px-md;
        transform: rotateY(180deg);
      }
    }

    .theme {
      position: absolute;
      font-weight: bold;
      width: $sm-img-per-max;
      text-align: center;
      white-space: nowrap;
      z-index: 3;
    }
  }

  .bg {
    background: $sm-bg-color-grey;
    position: fixed;
    z-index: -1;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
  }

  .outermostMargin {
    // padding: 0 $sm-spaceing-block-base 0 $sm-spaceing-block-base;

    background: $sm-bg-color-grey;
    color: $sm-text-color;
    font-size: $sm-font-size-lg;
    margin: 0px 0 0 0;

    .messageBox {
      // min-height: $sm-height-px-lg;
      margin: $sm-spacing-col-lg 0 0 0;
    }

    .etRowBox {
      margin: 0 0 $sm-spacing-col-lg 0;
      display: flex;
      flex-direction: row nowrap;
      justify-content: flex-start;

      .etButton {
        display: flex;
        flex-direction: column;
        align-items: center;
        width: $sm-img-per-mini;

        img {
          width: 50px;
          height: 50px;
          margin: $sm-spacing-row-lg $sm-spacing-row-base $sm-spacing-row-lg
            $sm-spacing-row-base;
        }

        .ideText {
          margin: 0 0 $sm-spacing-row-base 0;
          font-size: $sm-font-sizeVH-sm;
          font-weight: bold;
        }
      }
    }

    .rpIcon {
      margin: $sm-spacing-col-lg 0 $sm-spacing-col-lg 0;
      padding: $sm-spaceing-block-sm;

      .rpBox {
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        align-items: center;

        .title {
          display: flex;
          justify-content: flex-start;
          align-items: center;

          font-size: $sm-font-sizeVH-sm;
          img {
            height: $sm-icon-px-base;
          }
        }

        img {
          height: $sm-icon-px-md;
        }
      }
    }

    .buttons {
      display: flex;
      flex-direction: row;
      justify-content: space-around;
      align-items: center;
      margin-top: 30px;
      margin-bottom: 30px;
      .butItem {
        width: $sm-img-per-sm;
      }
    }
  }
}
</style>